package com.example.hqpatrol.fragment;

import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.example.hqpatrol.R;
import com.example.hqpatrol.adapter.ImageSelectGridAdapter;
import com.example.hqpatrol.base.BaseFragment;
import com.example.hqpatrol.common.util.GsonUtil;
import com.example.hqpatrol.databinding.FragmentFeedbackBinding;
import com.example.hqpatrol.entity.patrol.PatrolDetail;
import com.example.hqpatrol.entity.patrol.PatrolFeedback;
import com.luck.picture.lib.PictureSelectionModel;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.xuexiang.xhttp2.XHttp;
import com.xuexiang.xhttp2.callback.SimpleCallBack;
import com.xuexiang.xhttp2.callback.impl.IProgressResponseCallBack;
import com.xuexiang.xhttp2.exception.ApiException;
import com.xuexiang.xui.utils.SnackbarUtils;
import com.xuexiang.xui.widget.actionbar.TitleBar;
import com.xuexiang.xui.widget.edittext.materialedittext.MaterialEditText;
import com.xuexiang.xui.widget.spinner.materialspinner.MaterialSpinner;
import com.xuexiang.xutil.file.FileUtils;
import com.xuexiang.xutil.tip.ToastUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;

public class FeedbackFragment extends BaseFragment<FragmentFeedbackBinding> {

    private PatrolDetail patrolDetail;
    private PatrolFeedback patrolFeedback;
    private Map<String, String> pathAndIdMap = new HashMap<>();

    //图片选择
    private ImageSelectGridAdapter mAdapter;
    private List<LocalMedia> mediaList = new ArrayList<>();

    public FeedbackFragment(PatrolFeedback patrolFeedback, PatrolDetail patrolDetail) {
        this.patrolFeedback = patrolFeedback;
        this.patrolDetail = patrolDetail;
    }

    @NonNull
    @Override
    protected FragmentFeedbackBinding viewBindingInflate(LayoutInflater inflater, ViewGroup container) {
        return FragmentFeedbackBinding.inflate(inflater, container, false);
    }

    @Override
    protected TitleBar initTitle() {
        return null;
    }

    @Override
    protected void initViews() {
        TextView patrol_feedback_project = findViewById(R.id.patrol_feedback_project);
        patrol_feedback_project.setText(patrolFeedback.getProject());

        TextView patrol_feedback_content = findViewById(R.id.patrol_feedback_content);
        patrol_feedback_content.setText(patrolFeedback.getContent());

        TextView patrol_feedback_source = findViewById(R.id.patrol_feedback_source);
        patrol_feedback_source.setText(patrolFeedback.getSource());

        TextView patrol_feedback_remark = findViewById(R.id.patrol_feedback_remark);
        patrol_feedback_remark.setText(patrolFeedback.getRemark());

        MaterialSpinner patrol_feedback_result = findViewById(R.id.patrol_feedback_result);
        String result = patrolFeedback.getResult();
        if(StrUtil.isNotBlank(result)) patrol_feedback_result.setSelectedItem(result);
        patrol_feedback_result.setOnItemSelectedListener((view, position, id, item) -> {
            patrolFeedback.setResult(Convert.toStr(item));
        });

        MaterialEditText patrol_feedback_desc = findViewById(R.id.patrol_feedback_desc);
        String desc = patrolFeedback.getDesc();
        if(StrUtil.isNotBlank(desc)) patrol_feedback_desc.setText(desc);
        patrol_feedback_desc.setOnFocusChangeListener((view, b) -> {
            if(!b){
                patrolFeedback.setDesc(StrUtil.blankToDefault(patrol_feedback_desc.getText(), null));
                ToastUtils.toast(patrolFeedback.getDesc());
            }
        });

        if(patrolDetail.getStep() != 0){
            patrol_feedback_result.setEnabled(false);
            patrol_feedback_desc.setEnabled(false);
        }


        // 图片选择
        RecyclerView patrol_feedback_photo = findViewById(R.id.patrol_feedback_photo);
        GridLayoutManager manager = new GridLayoutManager(getContext(), 4, RecyclerView.VERTICAL, false);
        patrol_feedback_photo.setLayoutManager(manager);

        mAdapter = new ImageSelectGridAdapter(getContext(), () -> {
            PictureSelectionModel pictureSelectionModel = PictureSelector.create(this)
                    .openGallery(PictureMimeType.ofImage())
                    .maxSelectNum(6)
                    .minSelectNum(1)
                    .selectionMode(PictureConfig.MULTIPLE)
                    .previewImage(true)
                    .isCamera(true)
                    .enableCrop(false)
                    .compress(true)
                    .previewEggs(true);
            pictureSelectionModel.selectionMedia(mediaList);
            pictureSelectionModel.forResult(PictureConfig.CHOOSE_REQUEST);
        });
        patrol_feedback_photo.setAdapter(mAdapter);
        mAdapter.setSelectList(mediaList);
        mAdapter.setSelectMax(6);
        mAdapter.setOnItemClickListener((position, v) -> {
            PictureSelector.create(this).externalPicturePreview(position, mediaList);
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        System.out.println(requestCode);
        System.out.println(resultCode);
        System.out.println(data);

        if(requestCode == PictureConfig.CHOOSE_REQUEST){
            // 图片选择
            if(resultCode == -1){
                mediaList = PictureSelector.obtainMultipleResult(data);
                mAdapter.setSelectList(mediaList);
                mAdapter.notifyDataSetChanged();

                for(int i=0; i<mediaList.size(); i++){
                    LocalMedia localMedia = mediaList.get(i);
                    String path = localMedia.getPath();
                    //如果map中没有此媒体fileId,或者fileId的是空的，则开始上传
                    if(StrUtil.isBlank(MapUtil.getStr(pathAndIdMap, path)) || StrUtil.isBlank(StrUtil.split(MapUtil.getStr(pathAndIdMap, path), ",").get(0))){
                        XHttp.post("https://hqzn.shdsyy+.com.cn:18080/man/repairCross/upload")
                                .uploadFile("file", FileUtils.getFileByPath(path), (bytesWritten, contentLength, done) -> {

                                    //设置每张照片的上传进度百分比
                                    String bfb = NumberUtil.formatPercent(NumberUtil.div(bytesWritten, contentLength), 0);
                                    pathAndIdMap.put(path, "," + bfb);
                                    mAdapter.setPathAndIdMap(pathAndIdMap);
                                    notifyChange();

                                }).execute(new SimpleCallBack<Object>() {
                                    @Override
                                    public void onSuccess(Object response) throws Throwable {
                                        Map<String, Object> responseMap = GsonUtil.beanToMap(response);
                                        String fileId = MapUtil.getStr(responseMap, "fileId");
                                        if (ObjectUtil.equal(200, MapUtil.getInt(responseMap, "state")) && StrUtil.isNotBlank(fileId)){
                                            String url = "https://hqzn.shdsyy.com.cn:18080/man/repairCross/download?keyId=" + fileId;
                                            pathAndIdMap.put(path, url + "," + ImageSelectGridAdapter.ACHIEVE_TEXT);
                                        }else{
                                            pathAndIdMap.put(path, ",失败");
                                        }
                                        mAdapter.setPathAndIdMap(pathAndIdMap);
                                        notifyChange();
                                    }

                                    @Override
                                    public void onError(ApiException e) {
                                        e.printStackTrace();
                                        pathAndIdMap.put(path, ",错误");
                                        mAdapter.setPathAndIdMap(pathAndIdMap);
                                        notifyChange();
                                    }
                                });
                    }
                }

            }
        }
    }

    private void notifyChange() {
        Message msg = new Message();
        msg.what = 1;
        FeedbackFragment.this.handler.sendMessage(msg);
    }

    //从当前主线程处理更新adapter
    private final Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            if(msg.what == 1){
                mAdapter.notifyDataSetChanged();
            }
        }
    };

    public String getFinallyFileIds() {
        List<String> fileIdList = new ArrayList<>();
        mediaList.forEach(localMedia -> {
            String f = MapUtil.getStr(pathAndIdMap, localMedia.getPath());
            if(StrUtil.isNotBlank(f) && StrUtil.equals(ImageSelectGridAdapter.ACHIEVE_TEXT, StrUtil.split(f, ",").get(1))){
                String url = StrUtil.split(f, ",").get(0);
                fileIdList.add(url);
            }
        });
        if(mediaList.size() > fileIdList.size()){
            SnackbarUtils.Short(getView(), "存在有未上传成功的文件").warning().show();
        }
        return StrUtil.join(",", fileIdList);
    }

    public PatrolFeedback getFeedbackResult() {
        patrolFeedback.setFileUrl(getFinallyFileIds());
        return patrolFeedback;
    }

}